/*
 * bookmark-list.js
 */

if (typeof BookmarkList == "undefined") {
	var BookmarkList = {
		_log : new Logger("BookmarkList"),
		bookmarks : new Array()
	};

	BookmarkList.displayBookmarks = function() {
		try {
			BookmarkList.bookmarks = iForumDAO.getAllBookmarks();
			$.each(BookmarkList.bookmarks, function(i, bookmark) {
				var row = $("#template").clone();

				if (i % 2 == 0)
					row.attr("class", "even");
				else
					row.attr("class", "odd");

				row.find("#createtime").text(bookmark.createtime);
				var folder = iForumDAO.getFolder(bookmark.folderid);
				var topic = iForumDAO.getTopic(bookmark.topicid);
				var thread = iForumDAO.getThread(bookmark.threadid);

				var url = "chrome://iforum/content/forum/thread-list.html?topicid="
						+ topic.id
						+ "&"
						+ bookmark.condition
						+ "#"
						+ bookmark.threadid;
				var title = topic.title + " - " + thread.seqno + "¥";

				row.find("#bookmark").text(title);
				row.find("#bookmark").attr("href", url);

				row.find("#folder").text(folder.name);
				row.find("#folder").attr(
						"href",
						"chrome://iforum/content/forum/topic-list.html?folderid="
								+ folder.id);

				row.attr("bookmarkIdx", i);
				row.appendTo("#bookmark-table");
			});
		} catch (e) {
			BookmarkList._log.error("displayBookmarks: " + e);
		}
	};

	BookmarkList.deleteBookmark = function(elmt) {
		try {
			var tr = elmt.parentNode.parentNode;
			var bookmarkIdx = tr.getAttribute("bookmarkIdx");
			BookmarkList._log.debug("deleteBookmark: " + bookmarkIdx);
			var bookmark = BookmarkList.bookmarks[bookmarkIdx];
			if (bookmark) {
				iForumDAO.deleteBookmark(bookmark.id);
				var topic = iForumDAO.getTopic(bookmark.topicid);
				topic.bookmarkid = -1;
				iForumDAO.updateTopic(topic);

				var thread = iForumDAO.getThread(bookmark.threadid);
				thread.bookmarkflag = 0;
				iForumDAO.updateThread(thread);
				tr.parentNode.removeChild(tr);
			}
		} catch (e) {
			BookmarkList._log.error("toggleMark: " + e);
		}
	};

	$(document).ready(function() {
		try {
			BookmarkList.displayBookmarks();
		} catch (e) {
			BookmarkList._log.error("loading: " + e);
		}
	});
}
